package com.qdxwx.data.service.comment;

import com.qdxwx.common.page.PageRequest;
import com.qdxwx.common.utils.TKConvert;
import com.qdxwx.data.mapper.common.CommentMapper;
import com.qdxwx.data.service.website.WebsiteProfileService;
import com.qdxwx.models.comment.Comment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 评论模块server实现
 * Qdx NetSchool Platform
 * @author qdxwx
 * @updateTime 2022/5/25
 * @description
 */
@Service
public class CommentServiceImpl implements CommentService {

	@Autowired
	private CommentMapper commentMapper;
	@Autowired
	private WebsiteProfileService websiteProfileService;

	/**
	 * 查询评论
	 */
	@Override
	public Comment get(int commentId) {
		if (commentId <= 0) return null;
		return commentMapper.selectCommentById(commentId);
	}

	@Override
	public Comment get(Comment query) {
		if (query.getUserId() < 1 || query.getOtherId() < 1 || query.getTypeId() < 1) {
			return null;
		}
		return commentMapper.selectCommentByUser(query.getUserId(), query.getOtherId(), query.getTypeId(), query.getParentId());
	}

	@Override
	public int add(Comment comment) {
		comment.setAddTime(LocalDateTime.now());
		comment.setContent(websiteProfileService.replaceBadWords(comment.getContent()));
		int count = commentMapper.addComment(comment);
		//如果是回复,则更新评论上的回复数
		//todo: 后期要放在审核通过后处理
		if (comment.getParentId() > 0) {
			updateReplyCount(comment.getParentId(), 1);
		}
		return count;
	}

	/**
	 * 更新评论
	 */
	@Override
	public int update(Comment comment) {
		return commentMapper.updateComment(comment);
	}

	/**
	 * 更新状态
	 */
	@Override
	public int updateStatus(Comment comment) {
		return commentMapper.updateStatus(comment);
	}

	@Override
	public int updatePraiseCount(int commentId, int count) {
		if (commentId < 1) return 0;
		return commentMapper.updateCommentCount(commentId, "praiseCount", count);
	}

	@Override
	public int updateReplyCount(int commentId, int count) {
		if (commentId < 1) return 0;
		return commentMapper.updateCommentCount(commentId, "replyCount", count);
	}

	/**
	 * 删除评论
	 */
	@Override
	public int delete(int commentId) {
		Comment comment = get(commentId);
		//如果是二级回复 更新他的父级的评论数减一
		if (comment.getParentId() > 0) {
			updateReplyCount(comment.getParentId(), -1);
		}
		return commentMapper.delComment(commentId);
	}

	@Override
	public int count(Comment comment) {
		return commentMapper.count(comment);
	}

	@Override
	public List<Comment> getList(Comment comment, PageRequest page) {
		return commentMapper.selectCommentList(comment, page);
	}

	@Override
	public double getScore(Comment comment) {
		int count = count(comment);
		if (count < 1) return 4.5;//没有评论默认4.5分
		Double score = commentMapper.selectScore(comment);
		if (score == null) return 4.5;//没有评分默认4.5分，一般不会不存在没分
		score = score / count;
		return TKConvert.toDouble(String.format("%.1f", score), 4.5);
	}
}
